<?php

/**
 * 商品报名模型
 * File Name：GoodsBmModel,php.php
 * File Encoding：UTF-8
 * File New Time：2014-5-7 10:09:12
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class GoodsBmModel extends BaseModel {

    //每日审核不通过数量
    public $noCheckSum = 150;
    //每日邮寄样品数量
    public $noMailkSum = 100;

    //表名
    public function tableName() {
        return '{{goods_bm}}';
    }

    //返回模型对象
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            //编辑
            array('cat_id', 'required', 'message' => '商品分类不能为空！'),
            array('product_id', 'required', 'message' => '商品ID不能为空！'),
            //array('product_id', 'unique', 'message' => '该商品ID已经存在，不能重复报名！'),
            array('goods_name', 'required', 'message' => '商品标题不能为空！'),
            array('detail_url', 'required', 'message' => '商品地址不能为空！'),
            array('product_img', 'required', 'message' => '商品图片不能为空！'),
            array('p_price', 'required', 'message' => '商品原价不能为空！'),
            array('p_price', 'length', 'message' => '商品原价需要大于0！', 'min' => 0),
            array('sales', 'required', 'message' => '商品销量不能为空！'),
            array('start_time', 'required', 'message' => '商品活动开始日期不能为空！'),
            array('end_time', 'required', 'message' => '商品活动结束日期不能为空！'),
            array('note', 'statusNote', 'message' => '请填写审核操作原因！'),
            array('nick', 'isBlack', 'on' => 'insert'),
            //安全的。。。
            array('brand_id,tags,goods_brief,item_type,is_best,is_new,is_hot,level,click_url,home_img,module_img,status,note,message,listorder,moduleid,commission_rate,promo_price,nick,nick_add,state,city,freeshipping,stock,uid,admin_id,pay_status,isdelivery,status_savetime,is_show_wangwang,special_id,is_format', 'safe'),
        );
    }

    public function relations() {
        return array(
            'AdminUser' => array(self::BELONGS_TO, 'AdminUser', 'admin_id',),
        );
    }

    public function attributeLabels() {
        return array(
            'detail_url' => '商品地址',
            'goods_name' => '商品标题',
            'product_id' => '商品ID',
            'cat_id' => '商品分类',
            'p_price' => '原价',
            'promo_price' => '活动价格',
            'sales' => '销量',
            'product_img' => '商品图片',
            'goods_brief' => '商品简介',
            'special_id' => '专题ID',
        );
    }

    //数据保存后回调
    protected function afterSave() {
        //修改对应的推广记录
        GoodsSpreadModel::model()->saveGoodsStatus($this);
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->cat_id) {
            $this->moduleid = CategoryModel::model()->getModuleId($this->cat_id);
        }
        //时间处理
        if (!is_numeric($this->start_time)) {
            $this->start_time = strtotime($this->start_time);
        }
        if (!is_numeric($this->end_time)) {
            $this->end_time = strtotime($this->end_time);
        }
        //是否新增
        if ($this->isNewRecord) {
            $this->status_savetime = $this->add_time = time();
            $this->status = 0;
        } else {
            
        }
        return true;
    }

    public function isBlack($attribute, $params) {
        if (BlacklistModel::model()->isBlack($this->nick)) {
            $this->addError($attribute, '对不起，该宝贝暂时不能报名！旺旺[' . $this->nick . ']存在违规记录，暂时没有被解封或者已经拉入永久黑名单！');
            return false;
        }
        return true;
    }

    /**
     * 根据审核状态，检测是否需要填写操作理由
     * @param string 所要验证的特性的名字
     * @param array 验证规则中指定的选项
     */
    public function statusNote($attribute, $params) {
        if (in_array($this->status, array(2, 3)) && empty($this->note)) {
            $this->addError($attribute, '请填写审核操作原因！');
            return false;
        }
        return true;
    }

    /**
     * 检查每月报名数量
     * @param type $uid 用户UID
     * @return boolean
     */
    public function goodsMonthBmNumber($uid = '') {
        if (empty($uid)) {
            $uid = Yii::app()->user->uid;
            if (empty($uid)) {
                return false;
            }
        }
        //每月1号时间
        $monthTime = strtotime(date('Y-m-1'));
        //每月允许的报名总数
        $allow = ConfigModel::model()->getConfig('month_sign_up_sum');
        if ($allow == 0) {
            return true;
        }
        if ($allow < 0) {
            $this->addError('', "没有报名权限！");
            return false;
        }
        $count = $this->count($this->where(array('uid' => $uid, 'add_time' => array('GT', $monthTime), 'pay_status' => 0)));
        if ($count >= $allow) {
            $this->addError('', "您本月已经超过{$allow}次报名，请下个月再来！");
            return false;
        }
        return true;
    }

    /**
     * 获取同一个旺旺一天内报名多少次
     * @param type $nick 旺旺
     * @return boolean
     */
    public function goodsBmNumber($nick) {
        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = $start_time + 86400;
        $where = array(
            'nick' => $nick,
            'add_time' => array(array('GT', $start_time), array('LT', $end_time), 'and'),
            'status' => 0,
        );
        $count = $this->count($this->where($where));
        if ($count > 3) {
            $this->addError('', '同一店铺一天之内只能报名三个宝贝，今天的名额用完了，明天再来报名吧，感谢您对【' . ConfigModel::model()->getConfig('sitename') . '】的支持！');
            return false;
        } else {
            return true;
        }
    }

    /**
     * 编辑信息
     * @param type $data
     * @return boolean
     */
    public function editor($data) {
        if (empty($data)) {
            $this->addError('', '没有修改数据！');
            return false;
        }
        $model = $this->findByPk($data['goods_id']);
        if (empty($model)) {
            $this->addError('', '该信息不存在！');
            return false;
        }
        //原来状态
        $oldStatus = $model->status;
        //判断今日审核状态限制
//        if (in_array($data['status'], array(2, 3)) && $oldStatus != $data['status']) {
//            //每日审核未通过数量控制
//            if ($data['status'] == 2 && $this->noCheckSum($this->noCheckSum, 2) !== true) {
//                $this->addError('', '每日最多允许 ' . $this->noCheckSum . ' 条信息设置为审核未通过！');
//                return false;
//            }
//            //每日邮寄样品数据量控制
//            if ($data['status'] == 3 && $this->noCheckSum($this->noMailkSum, 3) !== true) {
//                $this->addError('', '每日最多允许 ' . $this->noMailkSum . ' 条信息设置为邮寄样品！');
//                return false;
//            }
//        }
        //审核不通过商品，在一定时间内可以修改状态，超过，禁止修改
        $baoming_no = (int) ConfigModel::model()->getConfig('baoming_no');
        if ($model->status == 2 && (time() - $model->status_savetime > $baoming_no * 86400)) {
            $this->addError('', '该商品过去太久，不允许修改！');
            return false;
        }
        $model->attributes = $data;
        //状态是否改变，更新时间
        if ($oldStatus != $model->status) {
            $model->status_savetime = time();
        }
        //付费报名处理，已付费处理
        if ($model->status == 2 && $model->pay_status == 2) {
            //改为退款中
            $model->pay_status = -1;
        }
        //记录操作人
        $model->admin_id = Yii::app()->passport->getUid();
        //明天上架的付费产品不能超过100个
        if ($model->status == 1 && $model->pay_status > 0) {
            if (!is_numeric($model->start_time)) {
                $start_time = strtotime($model->start_time);
            } else {
                $start_time = $model->start_time;
            }
            $count = $this->count($this->where(array('status' => 1, 'pay_status' => array('GT', 0), 'start_time' => $start_time)));
            if ($count >= 100) {
                $this->addError('', '付费产品同一天上架商品只能100个！');
                return false;
            }
        }
        if ($model->validate() && $model->save()) {
            //审核通过后，插入goods表
            if ($model->status == 1 && GoodsModel::model()->goodsBmAdd($model->attributes) == false) {
                $this->addErrors(GoodsModel::model()->getErrors());
                return false;
            }
            //记录审核操作记录
            if (GoodsActionModel::model()->goodsBmStatusActionLog($model) != true) {
                $this->addError('', GoodsActionModel::model()->getOneError());
                return false;
            }
            //状态改变，进行短信/邮件通知
            if ($oldStatus != $model->status) {
                try {
                    $this->snsNotice($model);
                } catch (Exception $exc) {
                    
                }
            }
            return true;
        }
        $this->addErrors($model->getErrors());
        return false;
    }

    /**
     * 审核状态标签
     * @param type $str 如果是字符串，获取对应键值，如果是数字，获取名称，为空，获取全部(数组)
     * @return array
     */
    public function getStatusTags($str = NULL) {
        $list = array(0 => '待审核', 1 => '审核通过', 2 => '审核不通过', 3 => '邮寄样品', 4 => '取消报名');
        if ($str === NULL) {
            return $list;
        } else {
            if (is_string($str)) {//传入字符，表示返回id
                return array_search($str, $list);
            } else {
                return isset($list[$str]) ? $list[$str] : false;
            }
        }
        return array();
    }

    /**
     * 根据管理员ID返回用户名
     * @staticvar array $username
     * @param type $uid
     * @return boolean
     */
    public function getByUidFindName($uid) {
        return AdminUser::model()->getByUidFindName($uid);
    }

    /**
     * 根据商品信息，返回审核状态。
     * @param type $data 商品信息
     * @return boolean|string
     */
    public function getHtmlStatus($data) {
        if (empty($data)) {
            return false;
        }
        if (is_object($data)) {
            $data = $data->attributes;
        }
        $str = '';
        if ($data['admin_id'] && $data['status'] == 0) {
            if (Yii::app()->controller->module->id == 'admin') {
                $str = '<font color="#0033FF">' . GoodsBmModel::model()->getByUidFindName($data['admin_id']) . "</font>正在审核中";
            } else {
                $str = '正在审核中';
            }
        } else {
            if ($data['status'] == 2) {
                $str = '审核不通过';
            } else if ($data['status'] == 1) {
                $str = '审核通过';
            } else if ($data['status'] == 3) {
                if ($data['isdelivery'] == 1) {
                    $str = '商家已邮寄样品';
                } else if ($data['isdelivery'] == 2) {
                    $str = '<font color="#FF0000">已收到邮寄样品</font>';
                } else {
                    $str = '等待邮寄样品';
                }
            } else if ($data['status'] == 4) {
                $str = '用户取消报名';
            } else {
                $str = '<label><input type="checkbox" value="1" style=" display:none">待审核 </label>';
            }
        }
        //付费
        if ($data['pay_status'] <> 0 && $data['pay_status'] >= -2) {
            if ($data['pay_status'] == 1) {
                $str .= ' <br/><font color="#FF0000">等待付款中</font>';
            } else if ($data['pay_status'] == 2) {
                $str .= ' <br/><font color="#FF0000">已付费</font>';
            } else if ($data['pay_status'] == -1) {
                $str .= ' <br/><font color="#FF0000">已付费，准备进行退款</font>';
            } else if ($data['pay_status'] == -2) {
                $str .= ' <br/><font color="#FF0000">已退款</font>';
            }
        }

        return $str;
    }

    /**
     * 返回邮寄样品状态
     * @return array
     */
    public static function getHtmlDelivery() {
        $list = array(0 => '等待邮寄样品', 1 => '商家已邮寄样品', 2 => '已收到邮寄样品');
        return $list;
    }

    /**
     * 根据状态，控制每日修改成对应状态数量总数控制
     * 检查用户今日审核不通过，操作数量是否超出限制，或者邮寄样品
     * @param type $noCheckSum 每日最多可以审核不通过数量，默认150
     * @return boolean
     */
    public function noCheckSum($noCheckSum = 150, $status = 2) {
        //如果是超级管理员，无视这个规则
        if (Yii::app()->passport->isAdministrator() === true) {
            return true;
        }
        $count = $this->count($this->where(array(
                    'admin_id' => Yii::app()->passport->getUid(),
                    'status' => $status,
                    'status_savetime' => array('EGT', strtotime(date('Y-m-d'))),
        )));
        if ($count >= $noCheckSum) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 更改对应报名信息的付费状态
     * @param type $model 报名对象
     * @param type $start_time 如果有设置时间
     * @return boolean
     */
    public function goodsBmPayChange($model, $start_time = '') {
        if (is_integer($model)) {
            $model = $this->findByPk($model);
        } else if (!is_object($model)) {
            return false;
        }
        if ($start_time && !is_numeric($start_time)) {
            $start_time = strtotime(date('Y-m-d 10:00:00', strtotime($start_time)));
        }
        if ($start_time > time()) {
            $end_time = $start_time + (86400 * 3);
            $model->start_time = $start_time;
            $model->end_time = $end_time;
        }
        $model->pay_status = 1;
        if ($model->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据item_type返回店铺类型名称
     * @param type $item_type 类型id
     * @return string
     */
    public function getShopTypeName($item_type) {
        switch ((int) $item_type) {
            case 1:
                return '天猫店';
                break;
            case 11:
                return '京东商城';
                break;
            case 0:
                return '淘宝店';
                break;
            default:
                return '淘宝店';
                break;
        }
    }

    /**
     * 报名宝贝分标签获取数据
     * @param type $label
     * @param type $page_num分页
     * @return type
     */
    public function getMemberBms($label, $page_num = 6) {
        $criteria = $this->where($this->conditionPro($label));
        $page_num = (int) $page_num < 0 ? 6 : $page_num;
        $count = $this->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = $page_num;
        $pager->applyLimit($criteria);
        $data = $this->findAll($criteria);
        return array($data, $pager);
    }

    /**
     * 页面获取标签统计数字
     * @return type
     */
    public function getGoodsBmCount() {
        $label = array(0, 1, 2, 3, 4, 5, 6);
        $key = "GoodsModel_getCount_{$label}";
        $count = Yii::app()->cache->get($key);
        if (!empty($count)) {
            return $count;
        }
        $count = array();
        foreach ($label as $key => $woa) {
            $criteria = $this->where($this->conditionPro($woa));
            $count[$key] = $this->count($criteria);
        }
        Yii::app()->cache->set($key, $count, 300);
        return $count;
    }

    /**
     * 根据筛选条件进行分标签
     * @param type $label,0=>待审核,1=>审核中 2=>邮寄样品 3=>等待排期  4=>审核未通过5=>上架  7=>下架
     * @return type
     */
    private function conditionPro($label) {
        $condition = array('uid' => Yii::app()->user->id, 'order' => 'goods_id desc');
        $time = time();
        switch ($label) {
            case 0:
                $condition['pay_status'] = 0;
                $condition['status'] = 0;
                break;
            case 1:
                $condition['pay_status'] = 0;
                $condition['admin_id'] = array('GT', 0);
                $condition['status'] = 0;
                break;
            case 2:
                $condition['pay_status'] = 0;
                // $condition['isdelivery'] = 1;
                $condition['status'] = 3;
                break;
            case 3:
                $condition['pay_status'] = 0;
                $condition['status'] = 1;
                $condition['start_time'] = array('GT', $time);
                break;
            case 4:
                $condition['pay_status'] = 0;
                $condition['status'] = 2;
                break;
            case 5:
                $condition['pay_status'] = 0;
                $condition['status'] = 1;
                $condition['start_time'] = array('LT', $time);
                $condition['end_time'] = array('GT', $time);
                break;
            case 6:
                $condition['pay_status'] = 0;
                $condition['status'] = 1;
                $condition['end_time'] = array('LT', $time);
                break;
        }
        return $condition;
    }

    /**
     * 已付费报名列表
     * @param type $uid
     * @param type $page_num
     * @return type
     */
    public function getMemberPayBms($uid, $page_num = 6) {
        $uid = (int) $uid;
        if (!$uid) {
            return array();
        }

        $criteria = new CDbCriteria();
        $criteria->addCondition('uid = :uid');
        $criteria->addCondition('pay_status != 0');
        $criteria->params = array(
            ':uid' => $uid,
        );
        $criteria->order = 'goods_id desc';
        $page_num = (int) $page_num < 0 ? 6 : $page_num;

        $count = $this->model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = $page_num;
        $pager->applyLimit($criteria);
        $ads = $this->findAll($criteria);
        return array($ads, $pager);
    }

    /**
     * 报名商品状态返回(操作)
     * @param type $model 该商品信息对象
     * @return type
     */
    public function getMemberBmMayAction($model) {
        if (!is_object($model)) {
            return;
        }
        $action = array();
        if ($model->status == 0 && $model->pay_status == 0 && $model->admin_id == 0) {
            $action[] = "<span class='bm_query_bj pd'><a href='" . Yii::app()->createUrl('user/goodsbm/bmedit', array('goods_id' => $model->goods_id)) . "'>编  辑</a></span></br>";
            $action[] = "<span class='bm_query_bj '><a href='" . Yii::app()->createUrl('user/goodsbm/cancel', array('goods_id' => $model->goods_id)) . "'>取消报名</a></span>";
        }
        if ($model->status == 0 && $model->pay_status == 1) {
            $action[] = "<div><a href='" . Yii::app()->createUrl('user/goodsbm/bmedit', array('goods_id' => $model->goods_id)) . "'>编辑</a></div>";
            $action[] = "<div><a href='" . Yii::app()->createUrl('user/goodsbm/cancel', array('goods_id' => $model->goods_id)) . "'>取消报名</a></div>";
            $action[] = "<div><a href='" . Yii::app()->createUrl('user/goodsbm/pay', array('goods_id' => $model->goods_id, 'undone' => 1)) . "'>继续完成付款</a></div>";
        }
        if ($model->status == 3) {
            if ($model->isdelivery == 0) {
                $action[] = "<div class='bm_query_dd'><a data-goods_id='{$model->goods_id}' href='" . Yii::app()->createUrl('user/goodsbm/specimen', array('goods_id' => $model->goods_id)) . "'class='bm_query_g'>确认邮寄样品</a></div>";
            } else if ($model->isdelivery == 1) { //用户提交了但我们还没有确认说已经收到的情况下可以修改
                $objModel = GoodsDeliveryModel::model()->findByPk($model->goods_id);
                if ($objModel) {
                    $action[] = "<input type='hidden' value='{$objModel->company}' name='company_{$model->goods_id}' id='company_{$model->goods_id}' />";
                    $action[] = "<input type='hidden' value='{$objModel->numbers}' name='numbers_{$model->goods_id}' id='numbers_{$model->goods_id}' />";
                    $action[] = "<div class='bm_query_dd'><a data-goods_id='{$model->goods_id}' href='" . Yii::app()->createUrl('user/goodsbm/specimen', array('goods_id' => $model->goods_id)) . "'class='bm_query_g'>修改订单号</a></div>";
                }
            }
        }
        if ($model->status == 0 && $model->pay_status == 0) {
            //$action[] = "<div><a href='" . Yii::app()->createUrl('user/bm/pay', array('goods_id' => $model->goods_id)) . "'>付款</a></div>";
        }
        $action[] = "<div class='bm_query_dd'><a href='" . Yii::app()->createUrl('user/goodsbm/query', array('goods_id' => $model->goods_id)) . "' class='bm_query_y' >进度查询 ></a></div>";
        return implode('', $action);
    }

    /**
     * 取消报名
     * @param type $data 数据对象
     * @return boolean
     */
    public function cancelBm($data) {
        if (!is_object($data)) {
            return false;
        }
        $data->status = 4; //取消报名
        $data->note = '用户取消报名';
        if ($data->validate() && $data->save(false)) {
            //增加记录
            GoodsActionModel::model()->goodsBmStatusActionLog($data);
            return true;
        }
        return false;
    }

    /**
     * 前台提交时，过滤一些敏感字段内容
     * @param type $data 数据
     * @return type
     */
    public function filterPostData(&$data) {
        $filter = array('is_best', 'is_new', 'is_hot', /* 'level', */ 'status', 'note', 'message', /* 'listorder', */ 'uid', 'admin_id', 'pay_status', 'isdelivery', 'status_savetime');
        foreach ($filter as $field) {
            if (isset($data[$field])) {
                unset($data[$field]);
            }
        }
        return $data;
    }

    /**
     * 需要事先为该模型赋上值,用来验证是否可以付费报名,如果可以则生成一条记录
     * @param  [type] $position   [description]
     * @param  [type] $controller [description]
     * @return [type]             [description]
     */
    public function checkPaybm($position_id) {
        $time = time();
        $return = array();
        $return['status'] = 0;
        //9是双11付费类型报名
        //10是妈咪街付费类型报名
        //7是正常的付费报名
        //根据不同的付费类型确定不同的键值...
        switch ($position_id) {
            case 9:
                $year = date('Y');
                $this->start_time = strtotime($year . '-11-11 00:00:00');
                $this->end_time = strtotime($year . '-11-14 00:00:00');
                break;
            default:
                if ($this->isNewRecord || $this->pay_status) {
                    $start_time = strtotime(Yii::app()->request->getParam('start_time'));
                    $this->start_time = strtotime(date('Y-m-d 10:00:00', $start_time));
                    $this->end_time = $start_time + 3 * 86400 + 36000;
                }
        }
        //根据不同的付费类型确定不同的验证方式
        switch ($position_id) {
            //这里基本上所有的付款类型都需要验证 
            case 0:
            case 7:
            case 8:
            case 9:
            case 10:
                empty($this->uid) ? $this->uid = Yii::app()->user->id : '';
                if (mb_strlen($this->goods_name, 'utf-8') < 7) {
                    $return['info'] = '商品标题长度不能少于7个字！';
                    return $return;
                }
                if (mb_strlen($this->goods_name, 'utf-8') > 10) {
                    $return['info'] = '商品标题长度不能超过十个字！';
                    return $return;
                }
                if (mb_strlen($this->goods_brief, 'utf-8') < 25) {
                    $return['info'] = '商品简介长度不能小于25个字！';
                    return $return;
                }
                if ($this->start_time <= $time) {
                    $return['info'] = '上架时间设置错误！';
                    return $return;
                }
                //只有在新增的报名商品才需要做这判断
                if ($this->isNewRecord) {
                    //检查同一个商品，有没有正在待付款的
                    $goods = $this->find($this->where(array('product_id' => $this->product_id, 'uid' => Yii::app()->user->id, 'order' => 'goods_id desc')));
                    if (!empty($goods)) {
                        if ($goods['status'] == 0 && $goods['pay_status'] == 1) {
                            $return['info'] = '该商品还没有完成支付，请支付完成后再次进行付费报名！';
                            return $return;
                        } else if ($goods['status'] == 0 && isset($goods['status']) && $goods['pay_status'] == 0) {
                            //如果已经分配给审核人员，但是该商品需要付费，强制取消分配。
                            if ($goods['admin_id']) {
                                $goods->admin_id = 0;
                                $goods->save(false);
                            }
                            //直接把原来的免费报名变成付费的
                            $return['info'] = '报名成功！';
                            $return['status'] = 1;
                            $return['url'] = Yii::app()->createUrl('/user/goodsbm/pay', array('goods_id' => $goods['goods_id'], 'position_id' => $position_id));
                            return $return;
                        } else if ($goods['status'] == 0 && isset($goods['status']) && $goods['start_time'] == $this->start_time) {
                            $return['info'] = '该商品已经有一个相同上架日期的商品在待审核状态！';
                            return $return;
                        }
                    }
                }
        }

        if ($this->save()) {
            //保存成功了后各自的逻辑各自再处理
        } else {
            $return['info'] = $this->getOneError();
            return $return;
        }

        //保存成功了后再各自的付款类型的逻辑处理,如果是妈咪街的则需要再调用接口把保存下来的数据发送给妈咪街
        //或者是付完款了之后再把数据发送到妈咪街
        return true;
    }

    /**
     * 加入短信邮件通知队列
     * @param type $object 报名数据对象
     * @return boolean
     */
    public function snsNotice($object) {
        if (empty($object) || !is_object($object)) {
            return false;
        }
        $uid = $object->uid;
        if (empty($uid)) {
            $this->addError('', '报名所属用户UID为空！');
            return false;
        }
        $user = MembersModel::model()->findByPk($uid);
        if (empty($user)) {
            $this->addError('', '该用户信息不存在！');
            return false;
        }
        if (empty($user->phone)) {
            $this->addError('', '手机号为空！');
            return false;
        }
        $data = array(
            'goods_id' => $object->goods_id,
            'product_id' => $object->product_id,
            'product_img' => $object->product_img,
            'goods_name' => $object->goods_name,
            'status' => $object->status,
            'add_time' => $object->add_time,
            'start_time' => $object->start_time,
            'end_time' => $object->end_time,
            'admin_id' => $object->admin_id,
            'uid' => $object->uid,
            'notice' => $object->note,
            'phone' => $user->phone,
            'email' => $user->email,
        );
        //调试模式关闭
        if (defined('YII_DEBUG') && YII_DEBUG == false) {
            //短信息与邮件通知
            RedisCluster::getInstance()->push('snsNotice', $data);
        }
        //后台报名审核通过时，通知对应的其他审核人员
        if ($object->status == 1) {
            $this->bmStatusNotice($object);
        }
        unset($object, $data);
        return true;
    }

    /**
     * 后台报名审核通过时，通知对应的其他审核人员
     * @param type $object
     * @return boolean
     */
    public function bmStatusNotice($object) {
        if (empty($object)) {
            return false;
        }
        $cat_id = $object->cat_id;
        $adminList = AdminCategoryModel::model()->getCategoryAdminList($cat_id);
        if (empty($adminList)) {
            return false;
        }
        $time = time();
        foreach ($adminList as $admin_id) {
            if ($admin_id == $object->admin_id) {
                continue;
            }
            //$key = "bmStatusNotice_{$admin_id}";
            $extendParams = array(
                'goods_id' => $object->goods_id,
                'product_img' => $object->product_img,
                'product_id' => $object->product_id,
                'promo_price' => $object->promo_price,
                'goods_name' => $object->goods_name,
                'goods_status' => $object->status,
                'add_time' => $object->add_time,
                'start_time' => date('Y-m-d H:i:s', $object->start_time),
                'end_time' => date('Y-m-d H:i:s', $object->end_time),
                'admin_id' => $object->admin_id,
                'admin_username' => AdminUser::model()->getByUidFindName($object->admin_id),
                'uid' => $object->uid,
                'notice' => $object->note,
                'time' => $time,
            );
            AdminMessage::model()->notice($admin_id, false, AdminMessage::goods, $extendParams);
            //MemcacheQueue::getInstance($key)->add($data);
        }
        return true;
    }

    /**
     * 创建搜索条件
     * @return [type] [description]
     */
    public function createSearchCriteria() {
        $criteria = new CDbCriteria;
        $criteria->compare('status', $this->status);
        $criteria->compare('admin_id', $this->admin_id);
        $criteria->compare('cat_id', $this->cat_id);
        $criteria->compare('product_id', $this->product_id);
        $criteria->compare('special_id', $this->special_id);
        if ($this->isdelivery > 2) {
            $criteria->addCondition("isdelivery > 0");
        } else {
            $criteria->compare('isdelivery', $this->isdelivery);
        }
        $criteria->compare('goods_name', $this->goods_name, true);
        $criteria->compare('nick', $this->nick, true);
        if (!empty($_GET['start_time'])) {
            $start_time = strtotime($_GET['start_time']);
            $criteria->addCondition("start_time >= $start_time");
        }
        if (!empty($_GET['end_time'])) {
            $end_time = strtotime($_GET['end_time']) + 86399;
            $criteria->addCondition("start_time <= $end_time");
        }
        if (!empty($_GET['add_start_time'])) {
            $start_time = strtotime($_GET['add_start_time']);
            $criteria->addCondition("add_time >= $start_time");
        }
        if (!empty($_GET['add_end_time'])) {
            $end_time = strtotime($_GET['add_end_time']) + 86399;
            $criteria->addCondition("add_time <= $end_time");
        }
        if (!empty($_GET['start_status_savetime'])) {
            $criteria->addCondition("status_savetime >= {$_GET['start_status_savetime']}");
        }
        if (!empty($_GET['end_status_savetime'])) {
            $criteria->addCondition("status_savetime < {$_GET['end_status_savetime']}");
        }
        return $criteria;
    }

    /**
     * 获取专场列表，默认取缓存
     * @param  boolean $cache [description]
     * @return [type]         [description]
     */
    public static function getSpecialHtmlList($cache = false) {
        $key = 'SpecialModel_name_list';
        $mixCache = Yii::app()->cache->get($key);
        if ($cache || empty($mixCache)) {
            $arrReturn = array();
            //$arrData = SpecialModel::model()->findAll(array('condition' => "status = 1"));
            $arrData = SpecialModel::model()->findAll();
            foreach ($arrData as $objData) {
                $arrReturn[$objData->id] = $objData->name;
            }
            Yii::app()->cache->set($key, $arrReturn);
            return $arrReturn;
        }
        return $mixCache;
    }

    /**
     * 默认取缓存
     * @param  boolean $cache [description]
     * @return [type]         [description]
     */
    public static function getDataForProduct_id($product_id, $cache = false) {
        $key = 'getDataForProduct_id_' . $product_id;
        $mixCache = Yii::app()->cache->get($key);
        if ($cache || empty($mixCache)) {
            $arrReturn = array();
            //$arrData = SpecialModel::model()->findAll(array('condition' => "status = 1"));
            $arrReturn = self::model()->find(array('condition' => 'product_id = :product_id', 'params' => array('product_id' => $product_id)));
            if ($arrReturn) {
                $arrReturn = $arrReturn->attributes;
            }
            Yii::app()->cache->set($key, $arrReturn);
            return $arrReturn;
        }
        return $mixCache;
    }

    public static function getSpecialHtmlDetail($data) {
        $arrData = self::getSpecialHtmlList();
        if (empty($arrData[$data])) {
            $arrData = self::getSpecialHtmlList(true);
        }
        return empty($arrData[$data]) ? '' : $arrData[$data];
    }

    public function getGoodsDelivery($goods_id) {

        return GoodsDeliveryModel::model()->findByPk($goods_id);
    }

    public function getGoodsNumbers($goods_id, $status = '', $page = 1, $pageSize = 20, $floCache = false) {
        $key = "GoodsBmModel_GoodsNumbers_{$page}_{$pageSize}_{$goods_id}_status{$status}";
        if ($floCache) {
            Yii::app()->cache->delete($key);
        }

        $cache = Yii::app()->cache->get($key);
        if ($cache) {
            return $cache;
        } else {
            $objCriteria = new CDbCriteria(array(
                'condition' => "product_id = :product_id AND goods_id != :goods_id",
                'params' => array('product_id' => $this->product_id, 'goods_id' => $this->goods_id),
                'order' => 'add_time desc',
            ));
            $objCriteria->compare("status", $status);

            $count = self::model()->count($objCriteria);


            $objCriteria->limit = $pageSize;
            $page = $page <= 0 ? 1 : $page;
            $objCriteria->offset = ($page - 1) * $pageSize;
            if ($objCriteria->offset < 0) {
                $objCriteria->offset = 0;
            }

            $arrData['data'] = self::model()->findAll($objCriteria);
            $arrData['count'] = $count;
            Yii::app()->cache->set($key, $arrData, 3600);
            return $arrData;
        }
    }

    public static function getCountForHmtl($arrData) {
        $html = '';
        $count = empty($arrData['count']) ? 0 : $arrData['count'];
        $html .= "<a href='javascript:void(0)'>{$count}</a>";
        if ($count) {
            $html .= "<br/><span  class='cat'>" . CategoryModel::getCat_nameForCount($arrData['cat']) . "</span>";
        }
        return $html;
    }

    /**
     * 根据设置的时间范围与时间戳字段获取报名列表的信息，返回的格式是数组
     * @param  [type] $start_time [起始时间戳]
     * @param  [type] $end_time   [结束时间戳]
     * @param  [type] $strField   [时间字段] 比如add_time(报名时间),status_savetime(状态变更时间)
     * @param  string $select     [选取键],
     * @return [type]             [返回数组格式]
     */
    public function getDataForAdd_time($start_time, $end_time, $strField, $select = '*', $addCondition = '', $model = '', $arrData = '') {
        $objCriteria = new CDbCriteria(array(
            'select' => $select,
        ));
        $condition = array();
        !empty($start_time) ? $condition[] = "{$strField} >= $start_time" : '';
        !empty($end_time) ? $condition[] = "{$strField} < $end_time" : '';
        if (!$condition) {
            return false;
        }
        $strCondition = implode(' and ', $condition);
        $objCriteria->condition = $strCondition;
        if ($addCondition) {
            if (is_string($addCondition)) {
                $objCriteria->addCondition($addCondition);
            } else {
                foreach ($addCondition as $val) {
                    $objCriteria->addCondition($val);
                }
            }
        }
        if ($arrData) {
            foreach ($arrData as $key => $val) {
                $objCriteria->$key = $val;
            }
        }

        if ($model == '') {
            $model = $this;
        } else {
            $model = new $model();
        }
        $command = $model->getCommandBuilder()->createFindCommand($model->getTableSchema(), $objCriteria, $model->getTableAlias());
        $arrGoodsDatas = $command->queryAll();
        return $arrGoodsDatas;
    }

}
